package com.hxzy.controller.mobile.login;


import cn.dev33.satoken.stp.SaLoginConfig;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.json.JSONUtil;
import com.hxzy.common.annotates.StpMobileCheckLogin;
import com.hxzy.common.aspect.satoken.StpMobileUtil;
import com.hxzy.common.resp.R;
import com.hxzy.common.util.RsaUtil;
import com.hxzy.controller.mobile.login.req.MobileLoginReq;
import com.hxzy.controller.mobile.login.resp.MobileLoginResp;
import com.hxzy.service.ContamerService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author wy
 * @Description TODO
 * @Date 2024/1/16 10:59
 * @Version 1.0
 */
@RestController
@RequestMapping(value = "/mobile")
@Api(tags = "手机-登录API")
public class MobileLoginController implements Cloneable {

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }

    @Autowired
    private ContamerService  contamerService;

    @ApiOperation(value = "登录")
    @PostMapping(value = "/login")
    public R<String> login(@RequestBody @Valid MobileLoginReq req){
       MobileLoginResp mobileLoginResp=this.contamerService.login(req);

        Map<String,Object> data=new HashMap<>();
        data.put("id",mobileLoginResp.getId());
        data.put("mobile",mobileLoginResp.getLoginId());
        data.put("userName",mobileLoginResp.getUserName());
        data.put("gender",mobileLoginResp.getGender());
        data.put("portrait",mobileLoginResp.getPortrait());

        //转json
        String jsonStr=JSONUtil.toJsonStr(data);

        //加密
        String enctryptInfo = RsaUtil.getRsa().encryptHex(jsonStr, KeyType.PublicKey);
        System.out.println(enctryptInfo);

        //SA-TOKEN多账户认证体系
         StpMobileUtil.login(mobileLoginResp.getId(), SaLoginConfig
                 .setExtra("info",enctryptInfo) );

        //生成令牌
        String token=StpMobileUtil.getTokenValue();
       return R.okHasData(token);
    }


    @StpMobileCheckLogin
    @ApiOperation(value = "手机端登出")
    @PostMapping(value = "/logout")
    public R adminLogout(){
        StpMobileUtil.logout();
        return R.ok();
    }


    @StpMobileCheckLogin
    @ApiOperation(value = "商家登录信息")
    @GetMapping(value = "/user/info")
    public R<MobileLoginResp>  userInfo(){
        //rsa加密的数据
        Object info = StpMobileUtil.getExtra("info");
        //解密
        String jsonStr = RsaUtil.getRsa().decryptStr(info.toString(), KeyType.PrivateKey);
        System.out.println(jsonStr);

        MobileLoginResp mobileLoginResp= JSONUtil.toBean(jsonStr, MobileLoginResp.class);

        return R.okHasData(mobileLoginResp);
    }


}
